package com.geyue.controller;

import com.geyue.common.toolbox.result.Res;
import com.geyue.core.model.Live;
import com.geyue.core.model.Teacher;
import com.geyue.core.service.LiveService;
import org.nutz.lang.random.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by Lyon on 2017/4/24.
 */
@Controller
@RequestMapping("/live")
public class LiveController {

    @Autowired
    private LiveService liveService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model,HttpSession session) {
        Teacher teacher = (Teacher) session.getAttribute("teacher");

        if(teacher == null)
            return "error";

        Live live = new Live();
        live.setTeacherId(teacher.getId());
        model.addAttribute("info",liveService.getOne(live));
        return "live";
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ResponseBody
    public Res add(Live live,HttpSession session) {
        Teacher teacher = (Teacher) session.getAttribute("teacher");

        if(teacher == null)
            return Res.fail("登录信息过时,请重新登录!");

        live.setTeacherId(teacher.getId());
        live.setStream(R.UU16());
        if(liveService.saveNotEmpty(live) > 0)
            return Res.success("创建成功!");

        return Res.fail("创建失败!");
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @ResponseBody
    public Res edit(Live live,HttpSession session) {
        Teacher teacher = (Teacher) session.getAttribute("teacher");

        if(teacher == null)
            return Res.fail("登录信息过时,请重新登录!");

        if(liveService.updateNotEmpty(live) > 0)
            return Res.success("修改成功!");

        return Res.fail("修改失败!");
    }


}
